<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>图书管理系统 - 相机测试</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    
    <!-- HarmonyOS 优化配置 -->
    <meta name="theme-color" content="#3880ff" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="default" />
    
    <!-- 应用样式 -->
    <link href="./css/chunk-ionic.f5c8e0e3.css" rel="stylesheet">
    <link href="./css/app.cd3d27f6.css" rel="stylesheet">
    
    <!-- 预加载关键资源 -->
    <link rel="preload" href="./css/app.css" as="style" />
    <link rel="preload" href="./js/app.js" as="script" />
    
    <!-- 样式文件 -->
    <link href="./css/app.css" rel="stylesheet" />
    <link href="./css/chunk-ionic.css" rel="stylesheet" />
    
    <style>
        /* HarmonyOS 适配样式 */
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f8f9fa;
            overflow: hidden;
        }
        
        #app {
            height: 100vh;
            width: 100vw;
        }
        
        /* 加载动画 */
        .loading-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, #3880ff, #5260ff);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            color: white;
            transition: opacity 0.3s ease;
        }
        
        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid rgba(255,255,255,0.3);
            border-top: 4px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .loading-container.hidden {
            opacity: 0;
            pointer-events: none;
        }
        
        /* 相机测试界面 */
        .camera-test-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: #f8f9fa;
            z-index: 8888;
            display: none;
            flex-direction: column;
            padding: 20px;
            box-sizing: border-box;
        }
        
        .camera-test-header {
            background: #3880ff;
            color: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .camera-test-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 15px;
            overflow-y: auto;
        }
        
        .camera-info-card {
            background: white;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .camera-button {
            background: #3880ff;
            color: white;
            border: none;
            padding: 15px 20px;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .camera-button:hover {
            background: #2d6ce8;
        }
        
        .camera-button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .photo-preview {
            max-width: 100%;
            max-height: 200px;
            border-radius: 8px;
            margin-top: 10px;
        }
        
        .status-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .status-success { background: #28a745; }
        .status-warning { background: #ffc107; }
        .status-error { background: #dc3545; }
        
        .debug-info {
            position: fixed;
            top: 10px;
            right: 10px;
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 8px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 10000;
            max-width: 200px;
        }
        
        .error-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: #f8f9fa;
            display: none;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 9998;
            padding: 20px;
            box-sizing: border-box;
        }
        
        .error-icon {
            font-size: 64px;
            color: #dc3545;
            margin-bottom: 20px;
        }
        
        .error-title {
            font-size: 24px;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
            text-align: center;
        }
        
        .error-message {
            font-size: 16px;
            color: #666;
            text-align: center;
            margin-bottom: 30px;
            line-height: 1.5;
        }
        
        .retry-button {
            background: #3880ff;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .retry-button:hover {
            background: #2d6ce8;
        }
    </style>
</head>
<body>
    <!-- 加载动画 -->
    <div class="loading-container" id="loading">
        <div class="loading-spinner"></div>
        <div>图书管理系统</div>
        <div style="font-size: 14px; margin-top: 10px;">正在加载相机测试...</div>
    </div>
    
    <!-- 相机测试界面 -->
    <div class="camera-test-container" id="cameraTest">
        <div class="camera-test-header">
            <h2>📷 相机功能测试</h2>
            <p>测试 HarmonyOS 相机集成</p>
        </div>
        
        <div class="camera-test-content">
            <!-- 平台信息 -->
            <div class="camera-info-card">
                <h3>🔧 平台信息</h3>
                <div id="platformInfo">
                    <div><span class="status-indicator status-warning"></span>检测中...</div>
                </div>
            </div>
            
            <!-- 相机状态 -->
            <div class="camera-info-card">
                <h3>📸 相机状态</h3>
                <div id="cameraStatus">
                    <div><span class="status-indicator status-warning"></span>检测中...</div>
                </div>
            </div>
            
            <!-- 相机操作 -->
            <div class="camera-info-card">
                <h3>🎯 相机操作</h3>
                <button class="camera-button" id="takePhotoBtn" onclick="testTakePhoto()">
                    📷 拍照测试
                </button>
                <button class="camera-button" id="checkPermissionBtn" onclick="checkCameraPermission()" style="margin-left: 10px;">
                    🔐 检查权限
                </button>
                <div id="photoResult" style="margin-top: 15px;"></div>
            </div>
            
            <!-- 测试日志 -->
            <div class="camera-info-card">
                <h3>📋 测试日志</h3>
                <div id="testLog" style="font-family: monospace; font-size: 12px; max-height: 150px; overflow-y: auto; background: #f5f5f5; padding: 10px; border-radius: 4px;">
                    <div>等待测试开始...</div>
                </div>
            </div>
            
            <!-- 返回按钮 -->
            <button class="camera-button" onclick="showMainApp()" style="background: #28a745;">
                🏠 返回主应用
            </button>
        </div>
    </div>
    
    <!-- 应用容器 -->
    <div id="app"></div>
    
    <!-- 错误界面 -->
    <div class="error-container" id="errorContainer">
        <div class="error-icon">⚠️</div>
        <div class="error-title">应用加载失败</div>
        <div class="error-message" id="errorMessage">
            应用在 5 秒内未能正常加载，请检查网络连接或重试。
        </div>
        <button class="retry-button" onclick="retryLoad()">🔄 重新加载</button>
    </div>
    
    <!-- 调试信息 -->
    <div class="debug-info" id="debug" style="display: none;">
        <div>🔧 HarmonyOS Debug</div>
        <div id="debug-status">初始化中...</div>
    </div>

    <script>
        // HarmonyOS 环境配置
        window.process = window.process || {};
        window.process.env = window.process.env || {};
        window.process.env.NODE_ENV = 'production';
        window.process.env.BASE_URL = './';
        window.process.env.VUE_APP_TITLE = '图书管理系统';
        
        // 全局变量
        let appMounted = false;
        let cameraTestMode = false;
        
        // 日志函数
        function addLog(message) {
            const logContainer = document.getElementById('testLog');
            if (logContainer) {
                const time = new Date().toLocaleTimeString();
                const logEntry = document.createElement('div');
                logEntry.textContent = `[${time}] ${message}`;
                logContainer.appendChild(logEntry);
                logContainer.scrollTop = logContainer.scrollHeight;
            }
            console.log('[Camera Test]', message);
        }
        
        // 调试函数
        function updateDebug(message) {
            const debug = document.getElementById('debug-status');
            if (debug) {
                debug.textContent = message;
            }
            console.log('[HarmonyOS Debug]', message);
        }
        
        // 隐藏加载动画
        function hideLoading() {
            const loading = document.getElementById('loading');
            if (loading) {
                loading.classList.add('hidden');
                setTimeout(() => {
                    loading.style.display = 'none';
                }, 300);
            }
        }
        
        // 显示错误界面
        function showError(message) {
            const errorContainer = document.getElementById('errorContainer');
            const errorMessage = document.getElementById('errorMessage');
            if (errorContainer && errorMessage) {
                errorMessage.textContent = message;
                errorContainer.style.display = 'flex';
            }
            hideLoading();
        }
        
        // 重新加载
        function retryLoad() {
            location.reload();
        }
        
        // 显示调试信息
        function showDebug() {
            const debug = document.getElementById('debug');
            if (debug) {
                debug.style.display = 'block';
            }
        }
        
        // 显示相机测试界面
        async function showCameraTest() {
            cameraTestMode = true;
            const cameraTest = document.getElementById('cameraTest');
            const app = document.getElementById('app');
            if (cameraTest && app) {
                cameraTest.style.display = 'flex';
                app.style.display = 'none';
            }
            hideLoading();
            
            // 异步初始化相机测试
            try {
                await initCameraTest();
            } catch (error) {
                addLog(`❌ 相机测试界面初始化失败: ${error.message}`);
            }
        }
        
        // 显示主应用
        function showMainApp() {
            cameraTestMode = false;
            const cameraTest = document.getElementById('cameraTest');
            const app = document.getElementById('app');
            if (cameraTest && app) {
                cameraTest.style.display = 'none';
                app.style.display = 'block';
            }
        }
        
        // 初始化相机测试
        async function initCameraTest() {
            addLog('开始相机测试初始化');
            
            try {
                // 检测平台信息
                detectPlatform();
                
                // 检测相机状态（异步）
                await detectCameraStatus();
                
                addLog('✅ 相机测试初始化完成');
            } catch (error) {
                addLog(`❌ 相机测试初始化失败: ${error.message}`);
            }
        }
        
        // 检测平台信息
        function detectPlatform() {
            const platformInfo = document.getElementById('platformInfo');
            if (!platformInfo) return;
            
            const platforms = [];
            const userAgent = navigator.userAgent;
            
            // 检测 HarmonyOS
            const isHarmonyOS = window.HarmonyOS || userAgent.includes('HarmonyOS');
            if (isHarmonyOS) platforms.push('HarmonyOS');
            
            // 检测其他平台
            if (userAgent.includes('Mobile')) platforms.push('移动端');
            if (userAgent.includes('Android')) platforms.push('Android');
            if (userAgent.includes('iPhone')) platforms.push('iOS');
            if (!userAgent.includes('Mobile')) platforms.push('桌面端');
            
            const platformText = platforms.length > 0 ? platforms.join(', ') : '未知平台';
            const statusClass = isHarmonyOS ? 'status-success' : 'status-warning';
            
            platformInfo.innerHTML = `
                <div><span class="status-indicator ${statusClass}"></span>${platformText}</div>
                <div style="font-size: 12px; color: #666; margin-top: 5px;">
                    UserAgent: ${userAgent.substring(0, 50)}...
                </div>
            `;
            
            addLog(`平台检测: ${platformText}`);
        }
        
        // 检测相机状态
        async function detectCameraStatus() {
            const cameraStatus = document.getElementById('cameraStatus');
            if (!cameraStatus) return;
            
            const supportedAPIs = [];
            let primaryAPI = null;
            let statusClass = 'status-error';
            
            // 检测 HarmonyOS 相机
            if (window.HarmonyOS && window.HarmonyOS.Plugins && window.HarmonyOS.Plugins.Camera) {
                supportedAPIs.push('HarmonyOS 原生相机');
                primaryAPI = 'HarmonyOS 原生相机';
                statusClass = 'status-success';
                addLog('✅ 检测到 HarmonyOS 原生相机');
            }
            
            // 检测 Capacitor 相机
            if (window.Capacitor && window.Capacitor.Plugins && window.Capacitor.Plugins.Camera) {
                supportedAPIs.push('Capacitor 相机');
                if (!primaryAPI) {
                    primaryAPI = 'Capacitor 相机';
                    statusClass = 'status-success';
                }
                addLog('✅ 检测到 Capacitor 相机');
            }
            
            // 检测 Web 相机 API
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                supportedAPIs.push('Web 相机 API');
                if (!primaryAPI) {
                    primaryAPI = 'Web 相机 API';
                    statusClass = 'status-success';
                }
                addLog('✅ 检测到 Web 相机 API');
                
                // 尝试检测可用的相机设备
                try {
                    const devices = await navigator.mediaDevices.enumerateDevices();
                    const videoDevices = devices.filter(device => device.kind === 'videoinput');
                    if (videoDevices.length > 0) {
                        addLog(`📹 发现 ${videoDevices.length} 个视频设备`);
                        videoDevices.forEach((device, index) => {
                            addLog(`  设备${index + 1}: ${device.label || '未知设备'}`);
                        });
                    } else {
                        addLog('⚠️ 未发现视频输入设备');
                    }
                } catch (enumError) {
                    addLog(`⚠️ 设备枚举失败: ${enumError.message}`);
                }
            }
            
            // 检测文件系统支持（用于照片保存）
            const hasFileSystem = !!(window.File && window.FileReader && window.FileList && window.Blob);
            if (hasFileSystem) {
                addLog('✅ 文件系统 API 支持');
            } else {
                addLog('⚠️ 文件系统 API 不支持');
            }
            
            // 生成状态显示
            let statusHTML = '';
            if (supportedAPIs.length > 0) {
                statusHTML = `
                    <div><span class="status-indicator ${statusClass}"></span>主要接口: ${primaryAPI}</div>
                    <div style="font-size: 12px; color: #666; margin-top: 5px;">
                        支持的接口: ${supportedAPIs.join(', ')}
                    </div>
                `;
                if (hasFileSystem) {
                    statusHTML += `<div style="font-size: 12px; color: #28a745; margin-top: 3px;">✅ 文件系统支持</div>`;
                }
            } else {
                statusHTML = `
                    <div><span class="status-indicator status-error"></span>❌ 未检测到相机支持</div>
                    <div style="font-size: 12px; color: #dc3545; margin-top: 5px;">
                        请检查设备权限或使用支持的浏览器
                    </div>
                `;
                addLog('❌ 未检测到任何相机支持');
            }
            
            cameraStatus.innerHTML = statusHTML;
        }
        
        // 检查相机权限
        async function checkCameraPermission() {
            const checkPermissionBtn = document.getElementById('checkPermissionBtn');
            if (checkPermissionBtn) checkPermissionBtn.disabled = true;
            
            addLog('开始检查相机权限');
            
            try {
                // 检查基础支持
                if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                    throw new Error('当前环境不支持 Web 相机 API');
                }
                
                // 检查权限状态（如果支持）
                if (navigator.permissions && navigator.permissions.query) {
                    try {
                        const permissionStatus = await navigator.permissions.query({ name: 'camera' });
                        addLog(`权限状态: ${permissionStatus.state}`);
                        
                        if (permissionStatus.state === 'denied') {
                            throw new Error('相机权限已被拒绝，请在浏览器设置中允许相机访问');
                        }
                    } catch (permError) {
                        addLog(`权限查询失败: ${permError.message}`);
                    }
                }
                
                // 尝试获取相机流
                let stream = null;
                try {
                    stream = await navigator.mediaDevices.getUserMedia({ 
                        video: { 
                            width: { min: 320, ideal: 640 },
                            height: { min: 240, ideal: 480 }
                        } 
                    });
                    
                    // 检查视频轨道
                    const videoTracks = stream.getVideoTracks();
                    if (videoTracks.length === 0) {
                        throw new Error('未找到可用的视频轨道');
                    }
                    
                    const track = videoTracks[0];
                    const settings = track.getSettings();
                    addLog(`✅ 相机权限检查通过`);
                    addLog(`相机分辨率: ${settings.width}x${settings.height}`);
                    addLog(`设备标签: ${track.label || '未知设备'}`);
                    
                    alert(`相机权限检查通过！\n分辨率: ${settings.width}x${settings.height}\n设备: ${track.label || '未知设备'}`);
                    
                } finally {
                    // 清理资源
                    if (stream) {
                        stream.getTracks().forEach(track => {
                            track.stop();
                            addLog(`已停止视频轨道: ${track.kind}`);
                        });
                    }
                }
                
            } catch (error) {
                let errorMessage = error.message;
                
                // 提供更友好的错误信息
                if (error.name === 'NotAllowedError') {
                    errorMessage = '相机权限被拒绝，请允许网站访问相机';
                } else if (error.name === 'NotFoundError') {
                    errorMessage = '未找到可用的相机设备';
                } else if (error.name === 'NotReadableError') {
                    errorMessage = '相机设备被其他应用占用';
                } else if (error.name === 'OverconstrainedError') {
                    errorMessage = '相机不支持请求的配置';
                } else if (error.name === 'SecurityError') {
                    errorMessage = '安全限制：请使用 HTTPS 访问';
                }
                
                addLog(`❌ 相机权限检查失败: ${errorMessage}`);
                alert(`相机权限检查失败: ${errorMessage}`);
            } finally {
                if (checkPermissionBtn) checkPermissionBtn.disabled = false;
            }
        }
        
        // 测试拍照功能
        async function testTakePhoto() {
            const takePhotoBtn = document.getElementById('takePhotoBtn');
            const photoResult = document.getElementById('photoResult');
            
            if (takePhotoBtn) takePhotoBtn.disabled = true;
            addLog('开始拍照测试');
            
            try {
                let photoData = null;
                
                // 尝试 HarmonyOS 原生相机
                if (window.HarmonyOS && window.HarmonyOS.Plugins && window.HarmonyOS.Plugins.Camera) {
                    addLog('使用 HarmonyOS 原生相机');
                    photoData = await window.HarmonyOS.Plugins.Camera.takePhoto({
                        quality: 90,
                        allowEdit: false,
                        resultType: 'base64'
                    });
                }
                // 尝试 Capacitor 相机
                else if (window.Capacitor && window.Capacitor.Plugins && window.Capacitor.Plugins.Camera) {
                    addLog('使用 Capacitor 相机');
                    photoData = await window.Capacitor.Plugins.Camera.getPhoto({
                        quality: 90,
                        allowEditing: false,
                        resultType: 'base64'
                    });
                }
                // 尝试 Web 相机
                else if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                    addLog('使用 Web 相机 API');
                    const stream = await navigator.mediaDevices.getUserMedia({ video: true });
                    
                    // 创建视频元素和画布来捕获照片
                    const video = document.createElement('video');
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    
                    video.srcObject = stream;
                    video.play();
                    
                    // 等待视频加载
                    await new Promise(resolve => {
                        video.onloadedmetadata = () => {
                            canvas.width = video.videoWidth;
                            canvas.height = video.videoHeight;
                            ctx.drawImage(video, 0, 0);
                            resolve();
                        };
                    });
                    
                    // 停止视频流
                    stream.getTracks().forEach(track => track.stop());
                    
                    // 获取图片数据
                    photoData = {
                        base64String: canvas.toDataURL('image/jpeg', 0.9).split(',')[1]
                    };
                }
                else {
                    throw new Error('没有可用的相机接口');
                }
                
                if (photoData && photoData.base64String) {
                    addLog('✅ 拍照成功');
                    if (photoResult) {
                        photoResult.innerHTML = `
                            <div style="color: #28a745; margin-bottom: 10px;">✅ 拍照成功！</div>
                            <img src="data:image/jpeg;base64,${photoData.base64String}" class="photo-preview" alt="拍摄的照片" />
                        `;
                    }
                } else {
                    throw new Error('未获取到照片数据');
                }
                
            } catch (error) {
                addLog(`❌ 拍照失败: ${error.message}`);
                if (photoResult) {
                    photoResult.innerHTML = `
                        <div style="color: #dc3545;">❌ 拍照失败: ${error.message}</div>
                    `;
                }
            } finally {
                if (takePhotoBtn) takePhotoBtn.disabled = false;
            }
        }
        
        // 监听应用挂载
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.target.id === 'app' && mutation.target.children.length > 0 && !appMounted) {
                    appMounted = true;
                    updateDebug('✅ 应用已挂载');
                    
                    // 检查是否需要显示相机测试
                    const urlParams = new URLSearchParams(window.location.search);
                    if (urlParams.get('test') === 'camera') {
                        showCameraTest();
                    } else {
                        hideLoading();
                    }
                    
                    // 检查路由
                    setTimeout(() => {
                        const routerOutlet = document.querySelector('ion-router-outlet');
                        if (routerOutlet) {
                            updateDebug('✅ 路由正常');
                            // 3秒后隐藏调试信息
                            setTimeout(() => {
                                const debug = document.getElementById('debug');
                                if (debug) debug.style.display = 'none';
                            }, 3000);
                        } else {
                            updateDebug('⚠ 路由异常');
                            showDebug();
                        }
                    }, 1000);
                }
            });
        });
        
        observer.observe(document.getElementById('app'), {
            childList: true,
            subtree: true
        });
        
        // 错误处理
        window.addEventListener('error', function(e) {
            const message = '脚本错误: ' + e.message.substring(0, 30);
            updateDebug('❌ ' + message);
            showError(message);
            showDebug();
        });
        
        window.addEventListener('unhandledrejection', function(e) {
            const message = 'Promise 错误: ' + String(e.reason).substring(0, 20);
            updateDebug('❌ ' + message);
            showError(message);
            showDebug();
        });
        
        // 超时检查
        setTimeout(() => {
            if (!appMounted && !cameraTestMode) {
                updateDebug('❌ 应用挂载超时');
                showError('应用在 5 秒内未能正常加载');
                showDebug();
            }
        }, 5000);
        
        // 初始化
        updateDebug('🚀 开始加载应用');
        
        // 检查是否直接进入相机测试模式
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('test') === 'camera') {
            setTimeout(() => {
                if (!appMounted) {
                    showCameraTest();
                }
            }, 2000);
        }
    </script>
    
    <!-- 应用脚本 -->
    <script defer="defer" src="./js/chunk-ionic-legacy.434e31d2.js" nomodule></script>
    <script defer="defer" src="./js/chunk-vendors-legacy.cd066ad9.js" nomodule></script>
    <script defer="defer" src="./js/app-legacy.069e3702.js" nomodule></script>
    <script defer="defer" type="module" src="./js/chunk-ionic.434e31d2.js"></script>
    <script defer="defer" type="module" src="./js/chunk-vendors.329624c4.js"></script>
    <script defer="defer" type="module" src="./js/app.705f933f.js"></script>
</body>
</html>